#include <cassert>
#include <new>
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <cmath>
#include <mutex>

#include "utils_mem.h"
#include "utils_mem_impl.h"
#include "utils_log.h"

namespace El {
namespace Utils {

/// Helper function to check if a number is a power of 2
inline bool IsPowerOfTwo(size_t n)
{
    return (n > 0) && ((n & (n - 1)) == 0);
}

/// 单件模式获取实例
BuddyInternal *BuddyInternal::GetInstance()
{
    static BuddyInternal buddyInternalInstance;
    return &buddyInternalInstance;
}

/// 构造函数，初始化内存池或系统内存管理
BuddyInternal::BuddyInternal() = default;

/// 析构函数，释放内存池或清理系统内存管理
BuddyInternal::~BuddyInternal() noexcept
{
    // 根据内存管理策略选择清理方式
    if (policy_ == Policy::kSystem) {
        SysDestroy();
        return;
    }

    if (policy_ == Policy::kPool) {
        DestroyPoolResources();
    }
}

void BuddyInternal::DestroyPoolResources() noexcept
{
    // 释放内存池资源
    if (originBuffer_ != nullptr) {
        // Use the configured free function
        memop_.free(originBuffer_);
        originBuffer_ = nullptr; // Avoid double free
        buffer_ = nullptr;
    }
    if (bufferList_ != nullptr) {
        ::free(bufferList_); // Management structures allocated with ::malloc
        bufferList_ = nullptr;
    }
    if (chunkHead_ != nullptr) {
        ::free(chunkHead_); // Management structures allocated with ::malloc
        chunkHead_ = nullptr;
    }
}

/// 计算一个数的以2为底的对数（向下取整）
/// \param x [in] 输入数值
/// \return log2(x)向下取整的结果
int BuddyInternal::Log2i(uint32_t x)
{
    int r = 31; // 从最高位开始检查

    if (!x)
        return 0;

    // 通过位运算快速计算log2
    if (!(x & 0xffff0000u)) {
        x <<= 16;
        r -= 16;
    }
    if (!(x & 0xff000000u)) {
        x <<= 8;
        r -= 8;
    }
    if (!(x & 0xf0000000u)) {
        x <<= 4;
        r -= 4;
    }
    if (!(x & 0xc0000000u)) {
        x <<= 2;
        r -= 2;
    }
    if (!(x & 0x80000000u)) {
        x <<= 1;
        r -= 1;
    }
    return r;
}

/// 打印所有内存节点的详细信息，用于调试
void BuddyInternal::PrintNodeInfo() const
{
    EL_DEBUG("--- Free List Details ---");
    for (int i = 0; i < bufferListCount_; ++i) {
        EL_DEBUG("List[{}] (Order {}, Size {}): Head={}, Prev={}, Next={}", i, i,
                 static_cast<size_t>(1) << (i + chunkNodeLog2_),
                 static_cast<const void *>(&(bufferList_[i].head)),
                 static_cast<const void *>(bufferList_[i].head.pre),
                 static_cast<const void *>(bufferList_[i].head.next));

        const ChunkNode *p = bufferList_[i].head.next;
        int count = 0;
        while (p != &(bufferList_[i].head)) {
            EL_DEBUG("  Node[{}]: Idx={}, Addr={}, Order={}, Self={}, Prev={}, Next={}", count, p->idx,
                     static_cast<const void *>(p->buf),
                     (p->order > 0 ? p->order - 1 : p->order),
                     static_cast<const void *>(p), static_cast<const void *>(p->pre),
                     static_cast<const void *>(p->next));
            p = p->next;
            count++;
            if (count > chunkCount_) {
                EL_ERROR("  Error: List possibly corrupted! Too many nodes.");
                break;
            }
        }
        if (count == 0) {
            EL_DEBUG("  (Empty)");
        }
    }
    EL_DEBUG("--- End Free List Details ---");
}

/// 配置内存管理策略和参数
/// \param policy [in] 内存管理策略
/// \param memop [in] 自定义内存操作函数集
/// \param param [in] 内存池策略的参数配置
void BuddyInternal::Configure(Policy policy, MemoryOperator *memop, PoolParameter *param)
{
    // Set policy first
    if (policy != Policy::kDefault && policy < Policy::kPolicyCount) {
        policy_ = policy;
    } else if (policy == Policy::kDefault) {
        // Define default policy (e.g., Pool for embedded, System for x86)
#ifdef __x86_64__ // Example check for x86_64
        policy_ = Policy::kSystem;
#else
        policy_ = Policy::kPool;
#endif
    }
    // else: invalid policy value, keep the default initialized policy_

    // Set custom memory operators if provided
    if (memop != nullptr) {
        // Basic checks for validity
        if (!memop->malloc || !memop->free || !memop->memcpy) {
            EL_ERROR("BuddyInternal::Configure Error: Invalid MemoryOperator provided.");
            // Decide on error handling: throw, assert, or fallback to defaults?
            // Falling back to default for now.
            memop_ = {.malloc = ::malloc, .free = ::free, .memcpy = ::memcpy};
        } else {
            memop_ = *memop;
        }
    }
    // else: use default memop_

    // Set pool parameters if provided and using pool policy
    if (param != nullptr) {
        param_ = *param; // Copy parameters
    }
    // else: use default param_

    // Initialize based on policy
    if (policy_ == Policy::kSystem) {
        SysInit();
        malloc_ = &BuddyInternal::SysMalloc;
        free_ = &BuddyInternal::SysFree;
        memcpy_ = &BuddyInternal::SysMemcpy;
        // alignSize_ setup for system malloc is tricky. We'll use the param if provided.
        if (param != nullptr) {
            alignSize_ = IsPowerOfTwo(param_.alignSize) ? param_.alignSize : 4; // Default align 4 if param is invalid
        } else {
            alignSize_ = 4; // Default if no params given
        }
    } else if (policy_ == Policy::kPool) {
        if (!InitializePoolParameters()) {
            EL_ERROR("BuddyInternal::Configure Error: Invalid Pool Parameters.");
            // Fallback to system policy?
            policy_ = Policy::kSystem;
            SysInit();
            malloc_ = &BuddyInternal::SysMalloc;
            free_ = &BuddyInternal::SysFree;
            memcpy_ = &BuddyInternal::SysMemcpy;
            return;
        }
        if (!AllocatePoolResources()) {
            EL_ERROR("BuddyInternal::Configure Error: Failed to allocate pool resources.");
            // Fallback to system policy
            policy_ = Policy::kSystem;
            SysInit();
            malloc_ = &BuddyInternal::SysMalloc;
            free_ = &BuddyInternal::SysFree;
            memcpy_ = &BuddyInternal::SysMemcpy;
            // Ensure partially allocated pool resources are freed
            DestroyPoolResources();
            return;
        }
        BuildFreeLists();

        malloc_ = &BuddyInternal::PoolMalloc;
        free_ = &BuddyInternal::PoolFree;
        memcpy_ = &BuddyInternal::PoolMemcpy;
        // alignSize_ is set in InitializePoolParameters

        // Output pool initialization info
        EL_INFO("Memory: Pool ready, {} MB available",
                static_cast<size_t>(param_.totalSize / (1024 * 1024)));

    } else {
        // Should not happen if policy enum is checked correctly
        EL_ERROR("BuddyInternal::Configure Error: Unknown policy!");
        // Fallback to system?
        policy_ = Policy::kSystem;
        SysInit();
        malloc_ = &BuddyInternal::SysMalloc;
        free_ = &BuddyInternal::SysFree;
        memcpy_ = &BuddyInternal::SysMemcpy;
    }
}

/// 从链表中删除节点
/// \param node [in] 要删除的节点指针
void BuddyInternal::DeleteNode(ChunkNode *node)
{
    node->order = 0;
    node->pre->next = node->next;
    node->next->pre = node->pre;
}

/// 向链表中插入节点
/// \param node [in] 要插入的节点指针
/// \param idx [in] 对应的链表索引
void BuddyInternal::InsertNode(ChunkNode *node, int idx)
{
    node->order = idx + 1;
    node->pre = &(bufferList_[idx].head);
    node->next = bufferList_[idx].head.next;
    bufferList_[idx].head.next->pre = node;
    bufferList_[idx].head.next = node;
}

/// 分割内存块
/// \param startIdx [in] 起始链表索引
/// \param endIdx [in] 目标链表索引
/// \return 分割后的块索引
int BuddyInternal::Split(int startIdx, int endIdx)
{
    // 从startIdx链表中取出第一个节点
    int idx = bufferList_[startIdx].head.next->idx;
    DeleteNode(bufferList_[startIdx].head.next);

    // 如果需要分割成更小的块
    if (startIdx > endIdx) {
        int size = 1 << (startIdx - 1);
        do {
            startIdx--;
            // 将第一个子块加入到startIdx-1链表中
            InsertNode(&(chunkHead_[idx]), startIdx);
            // 计算第二个子块的索引
            idx += size;
            size >>= 1;
        } while (startIdx > endIdx);
    }

    // 标记为分配状态
    chunkHead_[idx].order = -(endIdx + 1);

    return idx;
}

/// 合并内存块
/// \param blockIndex [in] 要合并的内存块索引
void BuddyInternal::Merge(int blockIndex)
{
    std::lock_guard<std::mutex> lock(mutex_); // RAII lock

    // 获取当前块的阶数
    int currentOrder = -(chunkHead_[blockIndex].order);

    // Attempt to merge with buddy iteratively
    while (currentOrder < bufferListCount_) {
        // Use the renamed FindBuddyIndex
        int buddyBlockIndex = FindBuddyIndex(blockIndex, currentOrder);

        // Secure Coding: Bounds check buddy index
        if (buddyBlockIndex >= chunkCount_ || chunkHead_[buddyBlockIndex].order != currentOrder)
            break;

        // 从链表中删除伙伴块
        DeleteNode(&chunkHead_[buddyBlockIndex]);

        // The combined block index is the lower of the two indices
        // Use the renamed FindCombinedIndex
        blockIndex = FindCombinedIndex(blockIndex, currentOrder);

        // Increase the order for the next iteration
        currentOrder++;
    }

    // 将合并后的块插入相应的链表
    InsertNode(&chunkHead_[blockIndex], currentOrder - 1);
}

/// 从内存池中分配内存块
/// \param size [in,out] 传入需要的大小，传出实际分配的大小
/// \return 分配的内存指针，失败返回NULL
void *BuddyInternal::PoolMalloc(size_t *size)
{
    // 计算需要的块大小对应的链表索引
    int vecIdx = Log2i(((*size - 1) >> (chunkNodeLog2_ - 1)));

    int idx = vecIdx;
    mutex_.lock();

    // 查找合适大小的空闲块
    while (idx < bufferListCount_) {
        if (bufferList_[idx].head.next != &(bufferList_[idx].head)) {
            break; // 找到了非空链表
        } else {
            idx++; // 继续查找更大的块
        }
    }

    // 没有找到合适的块
    if (idx >= bufferListCount_) {
        mutex_.unlock();
        EL_ERROR("Buddy No Free Space, totalSize:{} freeSize:{}", static_cast<uint32_t>(GetBufferSize()),
                 static_cast<uint32_t>(GetFreeSize()));
        return NULL;
    }

    // 分割空闲块
    idx = Split(idx, vecIdx);

    mutex_.unlock();

    // 计算实际分配的内存大小
    *size = ((1 << (vecIdx)) << chunkNodeLog2_);

    return chunkHead_[idx].buf;
}

/// 释放内存池中的内存块
/// \param ptr [in] 要释放的内存指针
void BuddyInternal::PoolFree(void *ptr)
{
    if (ptr == NULL) {
        return;
    }

    // 计算内存块索引
    int blockIndex = (reinterpret_cast<uint8_t *>(ptr) - buffer_) >> chunkNodeLog2_;
    assert(blockIndex >= 0);

    // 尝试合并空闲块
    Merge(blockIndex);
}

/// 使用 C++ 风格类型转换
template <class PT1, class PT2> inline bool PtrIsIn(PT1 *ptr, PT2 *start, size_t length)
{
    // Cast to const char* to avoid casting away const qualifier
    const char *pch_start = reinterpret_cast<const char *>(start);
    const char *pch_ptr = reinterpret_cast<const char *>(ptr);
    return pch_ptr >= pch_start && pch_ptr < pch_start + length;
}

/// 内存复制，如果源和目标都在管理的内存范围内，使用配置时指定的内存复制函数
/// \param dest [in] 目标内存地址
/// \param src [in] 源内存地址
/// \param size [in] 复制字节数
/// \return 目标内存地址
void *BuddyInternal::PoolMemcpy(void *dest, const void *src, size_t size)
{
    if (PtrIsIn(dest, buffer_, param_.totalSize) && PtrIsIn(src, buffer_, param_.totalSize)) {
        return memop_.memcpy(dest, src, size); // 使用自定义复制函数
    } else {
        return ::memcpy(dest, src, size); // 使用标准复制函数
    }
}

/// 获取管理的内存总字节数
/// \return 内存总字节数
size_t BuddyInternal::GetBufferSize() const
{
    if (policy_ == Policy::kPool) {
        return param_.totalSize;
    }

    return 0;
}

/// 获取管理的内存剩余字节数
/// \return 剩余可用内存字节数
size_t BuddyInternal::GetFreeSize() const
{
    if (policy_ == Policy::kPool) {
        mutex_.lock();
        size_t size = 0;
        int i = 0;

        // 计算所有空闲块的总大小
        for (i = 0; i < bufferListCount_; i++) {
            int tmp = 0;
            ChunkNode *p = bufferList_[i].head.next;
            while (p != &(bufferList_[i].head)) {
                tmp++;
                p = p->next;
            }

            size += (1 << i) * tmp;
        }
        mutex_.unlock();
        return size << chunkNodeLog2_;
    }

    return 0;
}

/// 打印内存节点的详细状态，用于调试
void BuddyInternal::DumpNodes() const
{
    if (policy_ == Policy::kSystem) {
        EL_INFO("CBuddy dump: SYS Policy");
        return;
    }

    EL_INFO("CBuddy: dump FreeList");
    PrintNodeInfo(); // 继续打印空闲列表详情

    // 计算已使用内存和百分比
    size_t totalSize = GetBufferSize();
    size_t freeSize = GetFreeSize();
    size_t usedSize = totalSize - freeSize;
    double usedPercentage = (totalSize > 0) ? (static_cast<double>(usedSize) * 100.0 / totalSize) : 0.0;

    EL_INFO("CBuddy: Pool Usage Summary");
    EL_INFO("  Total Size: {} bytes ({} KB)", totalSize, totalSize / 1024);
    EL_INFO("  Free Size : {} bytes ({} KB)", freeSize, freeSize / 1024);
    EL_INFO("  Used Size : {} bytes ({} KB)", usedSize, usedSize / 1024);
    EL_INFO("  Usage     : {:.2f}%", usedPercentage);
    return;
}

/// 配置内存管理策略和参数
/// \param policy [in] 内存管理策略
/// \param memop [in] 自定义内存操作函数集
/// \param param [in] 内存池策略的参数配置
void Buddy::Configure(Policy policy, MemoryOperator *memop, PoolParameter *param)
{
    BuddyInternal::GetInstance()->Configure(policy, memop, param);
}

/// 获取Buddy单例实例
/// \return Buddy单例对象指针
Buddy &Buddy::GetInstance()
{
    static Buddy buddyInstance;
    return buddyInstance;
}

/// 析构函数
Buddy::~Buddy() noexcept = default; // Nothing owned directly by Buddy wrapper

/// 构造函数
Buddy::Buddy()
{
    internal_ = BuddyInternal::GetInstance();
}

/// 获取内存池分配的总内存空间的起始地址
/// \return 内存池起始地址
uint8_t *Buddy::GetPoolBuffer() const
{
    if (internal_ == nullptr) {
        // This should ideally not happen if GetInstance works correctly.
        return nullptr;
    }
    return internal_->GetPoolBuffer();
}

/// 从管理的内存中申请内存块
/// \param size [in] 需要分配的内存大小（字节）
/// \return 分配的内存地址，失败返回NULL
void *Buddy::Malloc(size_t size)
{
    if (internal_ == nullptr) {
        return nullptr;
    }
    return internal_->Malloc(&size);
}

/// 释放内存块
/// \param p [in] 要释放的内存指针
void Buddy::Free(void *p)
{
    if (internal_ == nullptr) {
        return;
    }
    internal_->Free(p);
}

/// 内存复制操作
/// \param dest [in] 目标内存地址
/// \param src [in] 源内存地址
/// \param size [in] 要复制的字节数
/// \return 目标内存地址
void *Buddy::Memcpy(void *dest, const void *src, size_t size)
{
    if (internal_ == nullptr) {
        return dest; // Or handle error?
    }
    return internal_->Memcpy(dest, src, size);
}

/// 获取管理的内存总字节数
/// \return 内存总字节数
size_t Buddy::GetBufferSize() const
{
    if (internal_ == nullptr) {
        return 0;
    }
    return internal_->GetBufferSize();
}

/// 获取管理的内存剩余字节数
/// \return 剩余可用内存字节数
size_t Buddy::GetFreeSize() const
{
    if (internal_ == nullptr) {
        return 0;
    }
    return internal_->GetFreeSize();
}

/// 打印内存节点的状态，仅用于调试
void Buddy::DumpNodes() const
{
    if (internal_ == nullptr) {
        return;
    }
    internal_->DumpNodes();
}

void BuddyInternal::SysInit()
{
    EL_INFO("BuddyInternal: System Policy Initialized.");
    // Reset pool-specific members potentially set by defaults
    originBuffer_ = nullptr;
    buffer_ = nullptr;
    chunkHead_ = nullptr;
    bufferList_ = nullptr;
    chunkCount_ = 0;
    bufferListCount_ = 0;
}

void BuddyInternal::SysDestroy() noexcept
{
    EL_INFO("BuddyInternal: System Policy Shutdown.");
    // Nothing specific to destroy for system policy itself
}

bool BuddyInternal::InitializePoolParameters()
{
    // Validate parameters
    if (param_.chunkSize < 1024 || !IsPowerOfTwo(param_.chunkSize)) {
        EL_ERROR("BuddyInternal Error: chunkSize ({}) must be >= 1024 and a power of 2.", param_.chunkSize);
        return false;
    }
    if (param_.totalSize == 0 || param_.totalSize % param_.chunkSize != 0) {
        EL_ERROR("BuddyInternal Error: totalSize ({}) must be > 0 and a multiple of chunkSize ({}).",
                 param_.totalSize, param_.chunkSize);
        return false;
    }
    if (param_.alignSize < 1 || !IsPowerOfTwo(param_.alignSize)) { // Allow alignSize=1
        EL_ERROR("BuddyInternal Error: alignSize ({}) must be a power of 2.", param_.alignSize);
        // Defaulting alignSize to 1 if invalid?
        // param_.alignSize = 1;
        return false;
    }

    // Secure Coding: Check for potential overflow when calculating chunkCount
    if (param_.chunkSize == 0) { // Prevent division by zero
        EL_ERROR("BuddyInternal Error: chunkSize cannot be zero.");
        return false;
    }
    if (param_.totalSize / param_.chunkSize > static_cast<size_t>(std::numeric_limits<int>::max())) {
        EL_ERROR("BuddyInternal Error: Too many chunks requested, exceeds integer limits.");
        return false;
    }
    chunkCount_ = static_cast<int>(param_.totalSize / param_.chunkSize);
    if (chunkCount_ <= 0) {
        EL_ERROR("BuddyInternal Error: Calculated chunkCount ({}) is invalid.", chunkCount_);
        return false;
    }

    chunkMask_ = param_.chunkSize - 1;
    chunkNodeLog2_ = Log2i(static_cast<uint32_t>(param_.chunkSize));

    // Secure Coding: Check for potential overflow in bufferListCount calculation
    int maxOrder = Log2i(static_cast<uint32_t>(chunkCount_));
    if (maxOrder < 0 || maxOrder > 30) { // Practical limit check
        EL_ERROR("BuddyInternal Error: Invalid maxOrder ({}) calculated.", maxOrder);
        return false;
    }
    bufferListCount_ = maxOrder + 1;

    alignSize_ = param_.alignSize;

    return true;
}

bool BuddyInternal::AllocatePoolResources()
{
    // Secure Coding: Check for overflow when calculating allocation size
    size_t managementStructSize = 0;
    size_t chunkHeadTotalSize = static_cast<size_t>(chunkCount_) * sizeof(ChunkNode);
    size_t bufferListTotalSize = static_cast<size_t>(bufferListCount_) * sizeof(BufferList);

    // Use ::malloc for management structures as they exist outside the pool
    chunkHead_ = static_cast<ChunkNode *>(::malloc(chunkHeadTotalSize));
    if (chunkHead_ == nullptr) {
        EL_ERROR("BuddyInternal Error: Failed to allocate chunkHead_ array ({} bytes).", chunkHeadTotalSize);
        return false;
    }
    managementStructSize += chunkHeadTotalSize;

    bufferList_ = static_cast<BufferList *>(::malloc(bufferListTotalSize));
    if (bufferList_ == nullptr) {
        EL_ERROR("BuddyInternal Error: Failed to allocate bufferList_ array ({} bytes).", bufferListTotalSize);
        ::free(chunkHead_); // Clean up previously allocated memory
        chunkHead_ = nullptr;
        return false;
    }
    managementStructSize += bufferListTotalSize;

    // Allocate the main buffer using the configured allocator
    // Allocate extra space to allow for alignment adjustment
    size_t allocationSize = param_.totalSize + param_.chunkSize - 1; // Max needed for alignment
                                                                     // Secure Coding: Overflow check
    if (param_.totalSize > std::numeric_limits<size_t>::max() - (param_.chunkSize - 1)) {
        EL_ERROR("BuddyInternal Error: Pool allocation size calculation overflowed.");
        ::free(chunkHead_);
        ::free(bufferList_);
        chunkHead_ = nullptr;
        bufferList_ = nullptr;
        return false;
    }

    originBuffer_ = static_cast<uint8_t *>(memop_.malloc(allocationSize));
    if (originBuffer_ == nullptr) {
        EL_ERROR("BuddyInternal Error: Failed to allocate main pool buffer ({} bytes).", allocationSize);
        ::free(chunkHead_);
        ::free(bufferList_);
        chunkHead_ = nullptr;
        bufferList_ = nullptr;
        return false;
    }

    // Calculate aligned buffer start address
    uintptr_t addr = reinterpret_cast<uintptr_t>(originBuffer_);
    // Align to chunk size boundary
    size_t offset = ((addr + param_.chunkSize - 1) & ~chunkMask_) - addr;
    buffer_ = originBuffer_ + offset;

    EL_DEBUG("Memory: Pool allocated {} bytes", static_cast<size_t>(allocationSize));

    return true;
}

void BuddyInternal::BuildFreeLists()
{
    // Initialize all chunk nodes
    for (int i = 0; i < chunkCount_; ++i) {
        chunkHead_[i].order = 0; // Mark as initially unassigned to a free list
        chunkHead_[i].idx = i;
        chunkHead_[i].buf = buffer_ + (static_cast<size_t>(i) << chunkNodeLog2_);
        chunkHead_[i].pre = nullptr;
        chunkHead_[i].next = nullptr;
    }

    // Initialize free list heads
    for (int i = 0; i < bufferListCount_; ++i) {
        bufferList_[i].head.order = i + 1; // Store order+1 (consistent with original logic)
        bufferList_[i].head.buf = nullptr;
        bufferList_[i].head.idx = static_cast<uint32_t>(-1); // Invalid index for head
        bufferList_[i].head.pre = &(bufferList_[i].head);
        bufferList_[i].head.next = &(bufferList_[i].head);
    }

    // Populate free lists using the buddy algorithm decomposition
    int remainingChunks = chunkCount_;
    int currentChunkIndex = 0;

    for (int orderIndex = bufferListCount_ - 1; orderIndex >= 0 && remainingChunks > 0; --orderIndex) {
        int chunksInThisOrder = 1 << orderIndex;
        // Secure Coding: Check division by zero (shouldn't happen if chunksInThisOrder is power of 2 > 0)
        if (chunksInThisOrder == 0)
            continue;
        int numBlocksOfThisOrder = remainingChunks / chunksInThisOrder;

        ChunkNode *listTail = &(bufferList_[orderIndex].head);

        for (int i = 0; i < numBlocksOfThisOrder; ++i) {
            // Secure Coding: Check bounds before accessing chunkHead_
            if (currentChunkIndex < 0 || currentChunkIndex >= chunkCount_) {
                EL_ERROR("BuddyInternal Error: currentChunkIndex out of bounds during list build!");
                // This indicates a logic error in calculation, should not happen if params are valid
                return; // Abort list building
            }

            ChunkNode *newNode = &chunkHead_[currentChunkIndex];
            newNode->order = orderIndex + 1; // order stored is 1-based index

            // Insert at the end of the list (after listTail)
            newNode->pre = listTail;
            newNode->next = listTail->next; // Should be the head initially
            listTail->next->pre = newNode;  // Update head's pre
            listTail->next = newNode;

            listTail = newNode; // Move tail forward

            // Secure Coding: Check for overflow before addition
            int nextChunkIndex = currentChunkIndex;
            if (chunksInThisOrder > std::numeric_limits<int>::max() - currentChunkIndex) {
                EL_ERROR("BuddyInternal Error: Chunk index calculation overflow during list build!");
                return; // Abort
            }
            nextChunkIndex += chunksInThisOrder;
            currentChunkIndex = nextChunkIndex;
        }
        // Secure Coding: Check for overflow before multiplication
        int chunksConsumed = 0;
        if (numBlocksOfThisOrder > std::numeric_limits<int>::max() / chunksInThisOrder) {
            EL_ERROR("BuddyInternal Error: Chunks consumed calculation overflow during list build!");
            return; // Abort
        }
        chunksConsumed = numBlocksOfThisOrder * chunksInThisOrder;

        // Secure Coding: Check for underflow before subtraction
        if (chunksConsumed > remainingChunks) {
            EL_ERROR("BuddyInternal Error: Chunk remaining calculation underflow during list build!");
            return; // Abort
        }
        remainingChunks -= chunksConsumed;
    }

    if (remainingChunks != 0 || currentChunkIndex != chunkCount_) {
        EL_WARN(
            "BuddyInternal Warning: Chunk distribution mismatch during free list build! Remaining={}, Index={}, Total={}",
            remainingChunks, currentChunkIndex, chunkCount_);
    }
}

} // namespace Utils
} // namespace El
